<template>
	<view>
		<view class="body">
			<form @submit="loginByMobile">
				<view class="face-wapper">
					<image src="../../static/avatar.png" class="face"></image>
				</view>
				
				<view class="info-wapper">
					<label class="label">手机号</label>
					<input name="mobile" type="text" class="input" placeholder="请输入手机号" placeholder-class="graywords" @input="getPhone" :value="phoneNumber" v-model="phoneNumber"/>
				</view>
				
				<view class="info-wapper" style="margin-top: 40upx;">
					<label class="label">验证码</label>
					<input name="captcha" type="text" class="input" placeholder="请输入验证码" placeholder-class="graywords"/>
					<button class="captcha" type="primary" @click="getcaptcha()">获取验证码</button>
				</view>
				
				<button type="primary" form-type="submit" class="login">登录</button>
			</form>
		</view>

		<!-- 第三方登录H5不支持，所以隐藏掉 -->
		<view class="third-wapper">
			<view class="third-icos-wapper">
				<!-- 5+app 用qq/微信/微博 登录 小程序用微信小程序登录 h5不支持 -->
				<!-- #ifdef APP-PLUS -->
					<image src="../../static/qq.png" @click="appOAuthLogin('qq')" class="third-ico"></image>
					<image src="../../static/weixin.png"  @click="appOAuthLogin('weixin')" class="third-ico" style="margin-left: 80upx;"></image>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
					<button open-type='getUserInfo' @getuserinfo="wxLogin" class="third-btn-ico">
					</button>
				<!-- #endif -->
			</view>
		</view>
		
		<view class="agree">
			<label class="radio"><radio value="agree" checked="true"/>我已阅读并同意 服务协议 和 隐私政策</label>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	const univerifyInfoKey = 'univerifyInfo';

	export default {
		data() {
			return {
				title: 'login',
				providerList: [],
				phoneNumber: '',
				univerifyBtnLoading: false
			}
		},
		computed: {
			...mapState(['hasLogin', 'isUniverifyLogin', 'univerifyErrorMsg'])
		},
		onLoad() {
			// 获取服务供应商
			uni.getProvider({
				service: 'oauth',
				success: (result) => {
					this.providerList = result.provider.map((value) => {
						let providerName = '';
						switch (value) {
							case 'weixin':
								providerName = '微信登录'
								break;
							case 'qq':
								providerName = 'QQ登录'
								break;
							case 'sinaweibo':
								providerName = '新浪微博登录'
								break;
							case 'xiaomi':
								providerName = '小米登录'
								break;
							case 'alipay':
								providerName = '支付宝登录'
								break;
							case 'baidu':
								providerName = '百度登录'
								break;
							case 'toutiao':
								providerName = '头条登录'
								break;
							case 'apple':
								providerName = '苹果登录'
								break;
							case 'univerify':
								providerName = '一键登录'
								break;
						}
						return {
							name: providerName,
							id: value
						}
					});
		
				},
				fail: (error) => {
					console.log('获取登录通道失败', error);
				},
			});
		
			if (this.hasLogin && this.isUniverifyLogin) {
				this.getPhoneNumber(uni.getStorageSync(univerifyInfoKey)).then((phoneNumber) => {
					this.phoneNumber = phoneNumber
				})
			}
		},
		methods: {
			...mapMutations(['login', 'setUniverifyLogin']),
			...mapActions(['getPhoneNumber']),
			Toast(data, duration = 1000) {
				uni.showToast(Object.assign({}, data, {
					duration
				}))
			},
			tologin(provider) {
				if (provider.id === 'univerify') {
					this.univerifyBtnLoading = true;
				}
		
				// 一键登录已在APP onLaunch的时候进行了预登陆，可以显著提高登录速度。登录成功后，预登陆状态会重置
				uni.login({
					provider: provider.id,
					// #ifdef MP-ALIPAY
					scopes: 'auth_user', //支付宝小程序需设置授权类型
					// #endif
					success: async (res) => {
						console.log('login success:', res);
						this.Toast({
							title: '登录成功'
						})
						// 更新保存在 store 中的登录状态
						this.login(provider.id);
		
						// #ifdef APP-PLUS
						this.setUniverifyLogin(provider.id === 'univerify')
						switch (provider.id) {
							case 'univerify':
								this.loginByUniverify(provider.id, res)
								break;
							case 'apple':
								this.loginByApple(provider.id, res)
								break;
						}
						// #endif
		
						// #ifdef MP-WEIXIN
						console.warn('如需获取openid请参考uni-id: https://uniapp.dcloud.net.cn/uniCloud/uni-id')
						uni.request({
							url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/user-center',
							method: 'POST',
							data: {
								action: 'loginByWeixin',
								params: {
									code: res.code,
									platform: 'mp-weixin'
								}
							},
							success(res) {
								console.log(res);
								if (res.data.code !== 0) {
									console.log('获取openid失败：', res.result.msg);
									return
								}
								uni.setStorageSync('openid', res.data.openid)
							},
							fail(err) {
								console.log('获取openid失败：', err);
							}
						})
						// #endif
					},
					fail: (err) => {
						console.log('login fail:', err);
		
						// 一键登录点击其他登录方式
						if (err.code == '30002') {
							uni.closeAuthView();
							this.Toast({
								title: '其他登录方式'
							})
							return;
						}
		
						// 未开通
						if (err.code == 1000) {
							uni.showModal({
								title: '登录失败',
								content: `${err.errMsg}\n，错误码：${err.code}`,
								confirmText: '开通指南',
								cancelText: '确定',
								success: (res) => {
									if (res.confirm) {
										setTimeout(() => {
											plus.runtime.openWeb('https://ask.dcloud.net.cn/article/37965')
										}, 500)
									}
								}
							});
							return;
						}
		
						// 一键登录预登陆失败
						if (err.code == '30005') {
							uni.showModal({
								showCancel: false,
								title: '预登录失败',
								content: this.univerifyErrorMsg || err.errMsg
							});
							return;
						}
		
						// 一键登录用户关闭验证界面
						if (err.code != '30003') {
							uni.showModal({
								showCancel: false,
								title: '登录失败',
								content: JSON.stringify(err)
							});
						}
					},
					complete: () => {
						this.univerifyBtnLoading = false;
					}
				});
			},
			loginByUniverify(provider, res) {
				this.setUniverifyLogin(true);
				uni.closeAuthView();
		
				const univerifyInfo = {
					provider,
					...res.authResult,
				}
		
				this.getPhoneNumber(univerifyInfo).then((phoneNumber) => {
					this.phoneNumber = phoneNumber;
					uni.setStorageSync(univerifyInfoKey, univerifyInfo)
				}).catch(err => {
					uni.showModal({
						showCancel: false,
						title: '手机号获取失败',
						content: `${err.errMsg}\n，错误码：${err.code}`
					})
					console.error(res);
				})
			},
			async loginByApple(provider, res) {
				// 获取用户信息
				let getUserInfoErr, result
				// #ifndef VUE3
				[getUserInfoErr, result] = await uni.getUserInfo({
					provider
				});
				// #endif
				
				// #ifdef VUE3
				try {
					result = await uni.getUserInfo({
						provider
					});
				} catch(e) {
					getUserInfoErr = e
				}
				// #endif
				
				if (getUserInfoErr) {
					let content = getUserInfoErr.errMsg;
					if (~content.indexOf('uni.login')) {
						content = '请在登录页面完成登录操作';
					}
					uni.showModal({
						title: '获取用户信息失败',
						content: '错误原因' + content,
						showCancel: false
					});
				}
				// uni-id 苹果登录
				uni.request({
					url: 'https://97fca9f2-41f6-449f-a35e-3f135d4c3875.bspapp.com/http/user-center',
					method: 'POST',
					data: {
						action: 'loginByApple',
						params: result.userInfo
					},
					success: (res) => {
						console.log('uniId login success', res);
						if(res.data.code !== 0){
							uni.showModal({
								showCancel: false,
								content: `苹果登录失败: ${JSON.stringify(res.data.msg)}`,
							})
						} else {
							uni.setStorageSync('openid', res.data.openid)
							uni.setStorageSync('apple_nickname', res.data.userInfo.nickname)
						}
					},
					fail: (e) => {
						uni.showModal({
							content: `苹果登录失败: ${JSON.stringify(e)}`,
							showCancel: false
						})
					}
				})
			},
			getPhone(e) {
				this.phoneNumber = e.detail.value;
			},
			getcaptcha() {
				uni.request({
					url: this.$host + '/captcha',
					method: 'POST',
					data: {
						mobile: this.phoneNumber,
					},
					success(res) {
						uni.showToast({
							title: res.data.message,
							icon: "none",
							duration: 800
						})
					}
				})
			},
			loginByMobile(e) {
				let {mobile, captcha} = e.detail.value
				if(!mobile || !captcha) {
					uni.showToast({
						title: '请输入手机号与密码',
						icon: 'none',
						duration: 800
					})
					return
				}
				
				uni.request({
				    url: this.$host + '/login',
				    data: {
						'mobile': mobile,
						'captcha': captcha
				    },
					method: 'POST',
				    success: (res) => {
						console.log(res.data);
						if (res.data.code) {
							uni.showToast({
								title: '登录成功',
								icon: "none",
								duration: 800
							})
							return;
						}
						
						// 调用state中的属性
						// this.$store.state.hasLogin
						
						// 调用modules中的函数方法
						this.$store.commit('login', this.$store.state, res.data.data);//同步调用
						
						// 调用actions中的函数方法
						//this.$store.dispatch('login', this.$store.state, res.data.data);//异步调用
						
						// 本地缓存用户信息
						uni.setStorageSync("USER", res.data.data);
						
						// 登录成功跳转到我的
						uni.showToast({
							title: '登录成功',
							icon: "none",
							duration: 800
						})
						uni.switchTab({
							url: '../user/user'
						})
						
				    }
				});
			},
			// APP第三方登录
			appOAuthLogin(type) {
				// 授权
				uni.login({
					provider: type,
					success: e => {
						console.log(e, 333)
						// 获取用户信息
						uni.getUserInfo({
							provider: type,
							success: info => {
								let userInfo = info.userInfo
								let user = null
								if(type === 'weixin') {
									
									uni.request({
										url: this.$host + '/wxlogin',
										data: {
											nickname: infoRes.userInfo.nickName,
											avatar: infoRes.userInfo.avatarUrl,
											openid: infoRes.userInfo.openId,
											union_id: infoRes.userInfo.unionId,
											sex: infoRes.userInfo.gender,
											device_id: that.device_id,
											platform_type: that.platform_type,
											device_type: that.device_type,
										},
										method: 'POST'
									})
									.then(res => {    // 此处即为 success 回调中的 res
										console.log(res.data);
										const data = res.data
										//that.$store.commit('saveUser',{data,_that:that})
										uni.hideLoading()
										uni.showToast({
											title:res.msg
										})
									})
									.catch(err => {    // 此处即为 fail 回调中的 err
										console.error(err)
									})
									
									
									
								} else if(type === 'qq') {
									
								} else if(type === 'sinaweibo') {
									
								}
								// 需要与后台交互暂无接口仅前端缓存
								uni.setStorageSync("USER", user)
								// 登录成功跳转到我的
								uni.showToast({
									title: '登录成功',
									icon: "none",
									duration: 800
								})
								uni.switchTab({
									url: '../user/user'
								})
							} 
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.body {
		border-top: solid 1px #DBDBDA;
		padding: 0 40upx;
	}

	.face-wapper {
		display: flex;
		flex-direction: row;
		justify-content: center;
		margin-top: 120upx;
		margin-bottom: 120upx;
	}

	.face {
		width: 160upx;
		height: 160upx;
	}

	.info-wapper {
		display: flex;
		flex-direction: row;
		justify-content: center;
		border-bottom: solid 1px #DBDBDA;
		padding-bottom: 20upx;
	}

	.label {
		color: #808080;
	}

	.input {
		width: 500upx;
		margin-left: 40upx;
	}

	.graywords {
		color: #EAEAEA;
	}
	
    .captcha {
		position: fixed;
		right: 40upx;
		border-radius: 40upx;
		height: 60upx;
		font-size: 28rpx;
		justify-content: center;
		line-height: 60upx;
    }

	.login {
		margin-top: 60upx;
		width: 90%;
		border-radius: 50upx;
	}

	.third-wapper {
		width: 100%;
		position: fixed;
		bottom: 200upx;
		margin-left: 0;
		padding-right: 0;
	}

	.third-words {
		color: #A9A9A9;
		font-size: 13px;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.third-icos-wapper {
		margin-top: 30upx;
		display: flex;
		flex-direction: row;
		justify-content: center
	}

	.third-ico {
		width: 120upx;
		height: 120upx;
	}

	.third-btn-ico {
		background-image:url(../../static/weixin.png);
		width: 60upx;
		height: 60upx;
		background-color: white;
		background-size: 60upx 60upx;
		background-repeat:no-repeat;
		border:none;
		padding: 0;
	}
	button::after{
		border: none;
	}

	.agree {
		width: 100%;
		position: fixed;
		bottom: 60upx;
	}
	.radio {
		display: flex;
		justify-content: center;
	}
</style>
